package de.java.shortys.myhome.api.controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

import de.java.shortys.myhome.api.controller.navigation.NavigationController;
import de.java.shortys.myhome.api.view.AbstractSwingSubModuleView;
import de.java.shortys.myhome.api.view.IView;

public abstract class AbstractSwingSubModuleController implements IController {

	private AbstractSwingModuleController root;

	private IController parent;

	private List<IController> children = new ArrayList<IController>();

	private AbstractSwingSubModuleView view;

	public AbstractSwingSubModuleController(AbstractSwingModuleController root, IController parent,
			AbstractSwingSubModuleView view) {
		this.root = root;
		this.parent = parent;
		this.view = view;
		configureView();
	}

	@Override
	public boolean allowDeactivate() {
		return true;
	}

	@Override
	public void activate() {
		if (allowActivate() && !isActive()) {
			getRoot().getApplicationController().getView().activate(getView());
			getRoot().getApplicationController().getNavigationController().setActiveSubModuleController(this);
			onActivate();
		}
	}

	public void add(AbstractSwingSubModuleController child) {
		children.add(child);
		NavigationController.getInstance().add(child.getId(), child);
	}

	private void configureView() {
		this.view.setTitle(getTitle());
		this.view.addCloseListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				deactivate();
			}
		});
	}

	@Override
	public void deactivate() {
		if (allowDeactivate() && isActive()) {
			getRoot().getApplicationController().getView().deactivate(getView());
			getRoot().getApplicationController().getNavigationController().setActiveSubModuleController(null);
			view.clear();
			onDeactivate();
		}
	}

	@Override
	public List<IController> getChildren() {
		return children;
	}

	@Override
	public IController getParent() {
		return parent;
	}

	@Override
	public AbstractSwingModuleController getRoot() {
		return root;
	}

	@Override
	public IView getView() {
		return view;
	}

	@Override
	public boolean isActive() {
		return this.equals(getRoot().getApplicationController().getNavigationController()
				.getActiveSubModuleController());
	}

	public abstract boolean list();
}
